// src/config/sequelize.js
import { Sequelize } from "sequelize";
import dbConfig from "../../config/database.js";
import initProduct from "../models/product.model.js";
import initCategory from "../models/category.model.js";
import initSpecType from "../models/specType.model.js";
import initSku from "../models/sku.model.js"; // 添加这行
import initSkuSpec from "../models/skuSpec.model.js"; // 新增导入
import initSpecValue from "../models/specValue.model.js";
import initFile from "../models/file.model.js";
import initFileChunk from "../models/fileChunk.model.js";
import initUser from "../models/user.model.js";

class Database {
  constructor() {
    this.models = {};
    this.sequelize = new Sequelize(
      dbConfig.database,
      dbConfig.admin.user,
      dbConfig.admin.password,
      {
        host: dbConfig.host,
        port: dbConfig.port,
        dialect: "mysql",
        pool: dbConfig.admin.pool,
        logging: process.env.NODE_ENV === "development" ? console.log : false,
        define: {
          underscored: true,
          freezeTableName: true,
          timestamps: true,
          paranoid: true,
        },
        timezone: "+08:00",
      }
    );

    // 立即注册模型
    this.registerModels();
  }

  async testConnection() {
    try {
      await this.sequelize.authenticate();
      console.log("✅ MySQL 连接成功");
      return true;
    } catch (error) {
      console.error("❌ MySQL 连接失败:", error);
      throw error;
    }
  }

  registerModels() {
    console.log("开始注册模型...");

    // 注册模型
    this.models.Product = initProduct(this.sequelize);
    this.models.Category = initCategory(this.sequelize);
    this.models.SpecType = initSpecType(this.sequelize);
    this.models.Sku = initSku(this.sequelize); // 添加这行
    this.models.SkuSpec = initSkuSpec(this.sequelize); // 新增模型注册
    this.models.SpecValue = initSpecValue(this.sequelize);
    this.models.File = initFile(this.sequelize);
    this.models.FileChunk = initFileChunk(this.sequelize);
    this.models.User = initUser(this.sequelize);

    // 验证模型注册
    if (!this.models.Product) throw new Error("Product 模型注册失败");
    if (!this.models.Category) throw new Error("Category 模型注册失败");
    if (!this.models.SpecType) throw new Error("SpecType 模型注册失败");
    if (!this.models.Sku) throw new Error("Sku 模型注册失败"); // 添加这行
    if (!this.models.SkuSpec) throw new Error("SkuSpec 模型注册失败"); // 新增模型验证
    if (!this.models.SpecValue) throw new Error("SpecValue 模型注册失败");
    if (!this.models.File) throw new Error("File 模型注册失败");
    if (!this.models.FileChunk) throw new Error("FileChunk 模型注册失败");
    if (!this.models.User) throw new Error("User 模型注册失败");

    console.log("✅ 模型注册完成:", Object.keys(this.models));

    // 设置关联
    this.setupRelations();
  }

  setupRelations() {
    Object.values(this.models).forEach((model) => {
      if (typeof model.associate === "function") {
        model.associate(this.models);
      }
    });
    console.log("✅ 模型关联设置完成");
  }

  async syncModels(options = {}) {
    try {
      // 确保模型已注册
      if (Object.keys(this.models).length === 0) {
        this.registerModels();
      }

      await this.sequelize.sync({
        ...options,
        alter: { drop: false },
        hooks: false,
      });
      console.log("✅ 模型同步完成");
    } catch (error) {
      console.error("❌ 模型同步失败:", error);
      throw error;
    }
  }
}

// 创建并立即初始化数据库实例
const dbInstance = new Database();

// 测试连接并记录状态
dbInstance
  .testConnection()
  .then(() => console.log("数据库初始化完成"))
  .catch((err) => console.error("数据库初始化失败:", err));

export const db = dbInstance;
export const sequelize = dbInstance.sequelize;
